import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
// ServerSocketChannel 相当于 socket 编程的 ServerSocket , 用于创建服务器端通道

//通过ServerSocket监听本机上8888端口。如果有客户请求连接，则将该IP信息存入buffer并打印
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.wrap("Hello,world!!!".getBytes());
           //如果未指定buffer初始大小,则不能用 ByteBuffer.put((String).getBytes()) 来添加数据

        //创建通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //绑定端口
        socketChannel.socket().bind( new InetSocketAddress(8888));
        //设置非阻塞模式
        socketChannel.configureBlocking(false);
        System.out.println("Waiting for connection...");
        while(true){
            SocketChannel accept = socketChannel.accept();  //通过服务器端通道的accept()方法来获取客户端的 SocketChannel对象
            if(accept == null){
                System.out.println("null");
            }
            else{
                //获取请求连接的客户端的地址
                System.out.println("Connection from "  + accept.socket().getRemoteSocketAddress());
                buffer.rewind();  //将 position 设置为 0
                accept.write(buffer);
                System.out.println(buffer);
                accept.close();
            }
            Thread.sleep(2000);
        }
    }
}
